#ifndef GDFANG_H
#define GDFANG_H

#include <QWidget>
#include <QPainter>
#include <QStack>
#include <QVector>

class GDFang : public QWidget
{
    Q_OBJECT
public:
    explicit GDFang(QWidget *parent = nullptr);
    void resetGame();

protected:
    void paintEvent(QPaintEvent *event) override;
    void mousePressEvent(QMouseEvent *event) override;

private:
    enum Piece
    {
        EMPTY,
        PLAYER,
        AI_PIECE
    };
    enum GamePhase
    {
        PLACEMENT,
        REMOVAL,
        MOVEMENT
    };
    enum AIDifficulty
    {
        EASY,   // 只考虑当前步
        MEDIUM, // 3步前瞻
        HARD    // 5步前瞻+模式库
    };
    AIDifficulty aiLevel = MEDIUM;

    static const int BOARD_SIZE = 6;
    static const int CELL_SIZE = 80;

    struct MoveResult
    {
        bool isMove;
        int score;
        QPoint from;
        QPoint pos;
    };

    Piece board[BOARD_SIZE][BOARD_SIZE];
    GamePhase gamePhase;
    Piece currentPlayer;
    QPoint selectedPiece;
    QPoint removedPiece;
    int chances;
    QStack<QPoint> moveHistory;
    QVector<QPoint> vAvailableMoves;

    // 核心游戏逻辑
    void handlePlacement(QPoint pos);
    void handleRemoval(QPoint pos);
    void handleMovement(QPoint pos);
    bool isBoardFull() const;
    void gameOver();
    void switchPlayer();
    void aiMove();

    // 规则检查
    bool checkWinCondition() const;
    void checkSpecialRules(QPoint pos);
    int checkDiagonal(QPoint pos, int dir, Piece targetPlayer) const;
    int checkSquares(QPoint pos, Piece targetPlayer) const;
    bool checkDragon(QPoint pos, Piece targetPlayer) const;
    int evaluatePosition(const QPoint &pos, Piece player, bool bFirst = true);

    // 辅助功能
    bool isValidMove(QPoint pos) const;
    bool isValidPos(QPoint pos) const;
    bool isOnBorder(QPoint pos) const;
    bool isAdjacent(QPoint from, QPoint to) const;
    void placePiece(QPoint pos, Piece piece);
    void removePiece(QPoint pos);
    Piece getOpponent(Piece player) const;

    // AI功能
    QVector<MoveResult> generateMoves();
    MoveResult findBestMove(int depth);
    int minimax(int depth, bool maximizing, int alpha, int beta);
    int evaluateThreat(QPoint pos);
    int evaluateMove(QPoint from, QPoint to);
    int calculatePotential(QPoint pos, Piece piece);
    void aiRemovePiece();
    void aiMovePiece();
    void aiPlacePiece();

    // 绘图功能
    void drawBoard(QPainter &painter);
    void drawPieces(QPainter &painter);
    void drawSelection(QPainter &painter);
    void highlightAvailableMoves(QPainter &painter);
};

#endif // GDFANG_H